package com.smartStatus.admin.service.impl;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.smartStatus.admin.mapper.SysStudentStatusMapper;
import com.smartStatus.admin.service.SysFileService;
import com.smartStatus.admin.service.SysStudentStatusService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smartStatus.api.entity.SysStudentStatus;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.document.AbstractPdfStamperView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户学籍表 服务实现类
 * </p>
 *
 * @author lby
 * @since 2021-03-06
 */
@AllArgsConstructor
@Slf4j
@Service
public class SysStudentStatusServiceImpl extends ServiceImpl<SysStudentStatusMapper, SysStudentStatus> implements SysStudentStatusService {

    private final SysFileService sysFileService;

    /**
     * 用户导入个人学籍
     */
    @Override
    public void exportPdf(HttpServletResponse response, Map<String, Object> map) {
        // 错误数据
        Map<String, Object> map1 = new HashMap<>();
        // 设定pdf解析器
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
        // 设定请求
        response.setContentType("application/pdf");
        // 次数上线改为绝对地址
        File file = new File("pdf/学籍模板.pdf");
//        File file = new File("F:\\myWork\\graduation-project\\pdf\\模板.pdf");
        PdfReader pdfReader = null;
        PdfStamper pdfStamper = null;
        ServletOutputStream outputStream = null;
        try {
            // 读取原有pdf
            log.info("开始导出pdf----------------------------");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), "UTF-8"));
            outputStream = response.getOutputStream();
            pdfReader = new PdfReader(file.getAbsolutePath());
            // 生成一个新的pdf
            pdfStamper = new PdfStamper(pdfReader, outputStream);
            // 获取pdf表单
            AcroFields acroFields = pdfStamper.getAcroFields();
            // 设置pdf中文
            BaseFont font = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            acroFields.addSubstitutionFont(font);
            // 将数据加入pdf
            for (String key : map.keySet()) {
                if (!"".equals(map.get(key).toString()) && map.get(key) != null) {
                    if ("imageUrl".equals(key)) {
                        // 获取图片域的大小
                        int pageNo = acroFields.getFieldPositions("image").get(0).page;
                        Rectangle signRect = acroFields.getFieldPositions("image").get(0).position;
                        float x = signRect.getLeft();
                        float y = signRect.getBottom();
                        // 获取需要填充的图片，设置大小
                        String imageUrl = map.get("imageUrl").toString();
                        String substring = imageUrl.substring(21, imageUrl.length());
                        String image1 = sysFileService.getImageUrl("images", substring);
                        Image image = Image.getInstance(image1);
                        image.scaleToFit(signRect.getWidth(), signRect.getHeight());
                        image.setAbsolutePosition(x, y);
                        // 向页面中插入图片
                        PdfContentByte under = pdfStamper.getOverContent(pageNo);
                        under.addImage(image);
                    }
                    acroFields.setField(key, map.get(key).toString());
                } else {
                    map1.put(key, map.get(key).toString());
                    log.error("包含空数据:{}", map1);
                    throw new RuntimeException("包含空数据");
                }

            }
            pdfStamper.setFormFlattening(true);
            log.info("pdf导出成功:{}", map);
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
        // 关闭流
        finally {
            try {
                assert pdfStamper != null;
                pdfStamper.close();
                pdfReader.close();
                outputStream.close();
            } catch (DocumentException | IOException e) {
                e.printStackTrace();
            }

        }

    }
}
